﻿using System;
using System.Configuration;
using System.Text.RegularExpressions;

namespace TempEmployees.BLL.Validations
{
    public class Email
    {
        private static readonly string DEFAULT_EMAIL_REGEX_PATTERN = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        private static readonly string EMAIL_REGEX_PATTERN;

        private string m_email;

        static Email()
        {
            EMAIL_REGEX_PATTERN = ConfigurationManager.AppSettings["EMAIL_REGEX_PATTERN"];
            if (string.IsNullOrEmpty(EMAIL_REGEX_PATTERN)) EMAIL_REGEX_PATTERN = DEFAULT_EMAIL_REGEX_PATTERN;
        }

        public Email(string email)
        {
            m_email = email;
            if (!IsValid(m_email)) throw new ValidationErrorException();
        }

        public override string ToString()
        {
            return m_email;
        }

        public static bool IsValid(string email)
        {
            Regex rex = new Regex(EMAIL_REGEX_PATTERN);

            if (rex.IsMatch(email))
                return true;
            else
                return false;
        }

        public static bool IsValid(object data)
        {
            return IsValid(data as string);
        }
    }
}